package org.hilo.boot.scaffold;

import java.io.File;

import org.jretty.util.NestedRuntimeException;

import org.hilo.boot.core.UT;

/**
 * 组件添加示例（请参考这份代码）：
 * 
 * 添加 标准FastDFS组件
 * 
 * @author zollty
 * @since 2020年7月27日
 */
public class FastDfsPluginGenerator extends AbstractPluginGenerator {
    // 远程资源下载url
    private static final String SOURCE_FILE_URL = "http://10.2.10.51:8081/nexus/content/repositories/releases/"
            + "org/hilo/framework/fastdfs-spring-boot-starter-demo/1/fastdfs-spring-boot-starter-demo-1.zip";

    public FastDfsPluginGenerator() {
        // 赋值
        this.sourceFileUrl = SOURCE_FILE_URL;
    }
    
/**

1、依赖：
----------------------------------------------------------
    <dependency>
      <groupId>org.jretty</groupId>
      <artifactId>fastdfs-spring-boot-starter</artifactId>
      <version>1.0.0-SNAPSHOT</version>
    </dependency>

 */
    
    /**
     * 将文本配置添加到biz项目pom.xml的dependencies标签中（若为大锅型项目，则添加到app starter项目中），
     * 即 本方法和addStarterPomManagementDependency二选一，切勿重复添加!
     */
    @Override
    public String addBizPomManagementDependency() {
        return "    <dependency>\r\n      <groupId>org.jretty</groupId>\r\n      <artifactId>fastdfs-spring-boot-starter</artifactId>\r\n      <version>1.0.0-SNAPSHOT</version>\r\n    </dependency>";
    }
    
    @Override
    public String addParentPomManagementDependency() {
        return null;
    }

    @Override
    public String addStarterPomManagementDependency() {
        return null;
    }
    
/**

2、文本配置
----------------------------------------------------------
fastdfs: 
  tracker-servers: 192.168.11.242:22122
  socket-timeout: 5000
  connect-timeout: 2000
  pool:
    max-total: 128
    max-wait-millis: 100

 */
    /**
     * 将文本配置，添加到application-dev.yml配置中
     */
    @Override
    public String addDevYamlConfig() {
        String yamlConfigPath = UT.Path.connectPaths(source, YAML_CONFIG);
        return UT.File.getFileContent(yamlConfigPath);
    }

   
/**

3、代码配置及Demo
----------------------------------------------------------
参考配置：src/main/java/com/zollty/fast/example/demo/app/FastDfsConfig.java
@Configuration
public class FastDfsConfig {
    private String groupName = "group1";
    @Autowired
    private PooledFdfsClientFactory manager;
    @Bean
    public FdfsDownloader fdfsDownloader() {
        return new FdfsDownloader(manager, groupName);
    }
...

参考Demo：src/main/java/com/zollty/fast/example/demo/service/FastDfsDemoService.java

 */
    
    static final String OLD_PATH = "com/zollty/fast/example/demo";
    static final String OLD_PACK = "com.zollty.fast.example.demo";
    static final String JAVA_CONFIG1 = "src/main/java/com/zollty/fast/example/demo/app/FastDfsConfig.java";
    static final String JAVA_DEMO1 = "src/main/java/com/zollty/fast/example/demo/service/FastDfsDemoService.java";
    static final String YAML_CONFIG = "src/main/resources/application.yml";
    
    /**
     * 将代码和demo拷贝到 starterProjectPath 或 bizProjectPath 工程中
     */
    void copyProjectFiles() {
        String javaConfigSourcePath = UT.Path.connectPaths(source, JAVA_CONFIG1);
        // Rep为一个工具类，可以将fromPath的文件拷贝到toPath（toPath为null时为在源文件上替换）
        // 同时可以对文本内容进行替换（replace）、删除(deleteLine)、追加(append)等操作（具体参见其api）
        Rep.build(javaConfigSourcePath, UT.Path.replace(javaConfigSourcePath.replace(OLD_PATH, newPackagePath), source, starterProjectPath))
            .replace(OLD_PACK, basePackage).apply(false);
        
        if(separateBizApp) { // 业务与配置分离型项目（整个项目至少有一个xxx工程[入口,starter]和xxx-biz[业务代码]工程）
            String javaDemoSourcePath = UT.Path.connectPaths(source, JAVA_DEMO1);
            Rep.build(javaDemoSourcePath, UT.Path.replace(javaDemoSourcePath.replace(OLD_PATH, newPackagePath), source, bizProjectPath))
                .replace(OLD_PACK, basePackage).apply(false);
        } else { // 大锅型项目（整个项目只有一个xxx-app工程[入口,starter及业务代码]）
            String javaDemoSourcePath = UT.Path.connectPaths(source, JAVA_DEMO1);
            Rep.build(javaDemoSourcePath, UT.Path.replace(javaDemoSourcePath.replace(OLD_PATH, newPackagePath), source, starterProjectPath))
                .replace(OLD_PACK, basePackage).apply(false);
        }
    }

    protected File tempPath;
    // 调用入口
    @Override
    public void prepareAndMergeSource() {
        // 从系统temp目录创建一个临时工作文件夹
        tempPath = SgTools.createTempDir(UT.Random.getRadomStr09az(10));
        tempPath.deleteOnExit();
        logger.info("------------------tempPath=" + tempPath);
        
        // 通过http从远程下载source文件
        if (source == null) {
            String sourceNewZipPath = UT.Path.normalPath(tempPath.getAbsolutePath() + "/hilo-plugin-source.zip");
            if(getSourceFile(sourceNewZipPath)) {
                source = sourceNewZipPath;
            } else {
                throw new NestedRuntimeException("source is null");
            }
        }
        // 解压source文件
        if (source.endsWith(".zip")) {
            String sourceNewPath = UT.Path.normalPath(tempPath.getAbsolutePath() + "/hilo-plugin-source/");
            try {
                ZipUtils.unzipFile(sourceNewPath, source);
                source = sourceNewPath;
            } catch (Exception e) {
                throw new NestedRuntimeException(e);
            }
        }
        
        // 执行文件解析和拷贝逻辑
        try {
            copyProjectFiles();
        } catch(Exception e) {
            throw new NestedRuntimeException(e);
        }
    }

    /**
     * 执行完后清理资源
     */
    @Override
    public void clean() {
        if (tempPath != null) {
            UT.File.deleteAll(tempPath);
            tempPath = null;
        }
    }

}
